package com.woniu.realm;

import com.woniu.dao.AdminMapper;
import com.woniu.dao.MenusMapper;
import com.woniu.pojo.Admin;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 自定义域
 */
public class CustomRealm extends AuthorizingRealm {

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private MenusMapper menusMapper;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //获取登录认证成功的主体
        Admin admin = (Admin)principals.getPrimaryPrincipal();
        //根据角色Id查询权限
        List<String> perms = menusMapper.findPermsByRoles(admin.getRoleId());
        //对集合中的字符串做过滤处理，去除 空字符串及null
        perms = perms.stream().filter(s->s != null && !s.isEmpty()).collect(Collectors.toList());
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addStringPermissions(perms);
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //获取通过subject提交的主体信息
        String userName = (String)token.getPrincipal();
        Admin admin = adminMapper.selectByUserName(userName);
        if(admin == null){
            throw new UnknownAccountException("账号不存在");
        }
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(admin,admin.getPassword(),ByteSource.Util.bytes(admin.getSalt()),super.getName());
        info.setCredentialsSalt(ByteSource.Util.bytes(admin.getSalt()));
        return info;
    }
}
